package sky.demos.jpmml;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXBException;

import org.dmg.pmml.FieldName;
import org.dmg.pmml.PMML;
import org.jpmml.evaluator.FieldValue;
import org.jpmml.evaluator.InputField;
import org.jpmml.evaluator.ModelEvaluator;
import org.jpmml.evaluator.ModelEvaluatorFactory;
import org.xml.sax.SAXException;

public class PmmlDemo {
	public static void main(String[] args) throws IOException, SAXException, JAXBException {
		PMML pmml;

		String name = "/estimator.pmml";
		try (InputStream is = PmmlDemo.class.getResourceAsStream(name)) {
			pmml = org.jpmml.model.PMMLUtil.unmarshal(is);
			ModelEvaluatorFactory modelEvaluatorFactory = ModelEvaluatorFactory.newInstance();
			ModelEvaluator<?> modelEvaluator = modelEvaluatorFactory.newModelEvaluator(pmml);

			//测试数据
			HashMap<String, Object> testSample = new HashMap<String, Object>();
			testSample.put("c0", 1);
			testSample.put("c1", 2);
			testSample.put("c2", 3);
			testSample.put("c3", 4);
			testSample.put("c4", 5);
			testSample.put("c5", 6);

			//测试数据转换为pmml的数据结构
			Map<FieldName, FieldValue> arguments = new LinkedHashMap<FieldName, FieldValue>();
			List<InputField> inputFields = modelEvaluator.getInputFields();
			for (InputField inputField : inputFields) {
				FieldName inputFieldName = inputField.getName();
				FieldValue inputFieldValue = inputField.prepare(testSample.get(inputFieldName.getValue()));
				arguments.put(inputFieldName, inputFieldValue);
			}

			//计算
			Map<FieldName, ?> evaluate = modelEvaluator.evaluate(arguments);
			System.out.println("evaluate result：" + evaluate.get(new FieldName("_target")));

		}
	}
}
